//
// Created by wangjunjun on 2024/3/19.
//

#include "SyncTimer.h"
#include "../common/log/log.h"
#include <cstdlib>
#include <cstring>
#include<unistd.h>
std::unique_ptr<CSyncTimer> CSyncTimer::m_InStance= nullptr;
std::once_flag CSyncTimer::m_flag;

CSyncTimer::CSyncTimer(){

}
CSyncTimer::~CSyncTimer(){
    Stop();
}
CSyncTimer& CSyncTimer::GetInStance() {
    std::call_once(m_flag,[](){
        m_InStance.reset(new CSyncTimer());
    });

    return  *m_InStance;
}
void CSyncTimer::Start() {
    //创建线程
    m_DoSyncThread = std::thread(&CSyncTimer::DoTimerSyncJob, this);
    m_DoSyncThread.detach();
    return;
}

void CSyncTimer::Stop() {
    if(m_DoSyncThread.joinable())
        m_DoSyncThread.join();
}
//设置时间校准服务进程
void CSyncTimer::DoTimerSyncJob() {
    //
    SetSyncTimer();
   // while(true)
      {
        int time = 1800;
        do
        {
            time = sleep(1800);   //控制半个小时再次执行一次
        } while (time > 0);
        SetSyncTimer();
    }
}

void CSyncTimer::SetSyncTimer(){
    const char* password = "wjj2017!";
    const char* command = "sudo ntpdate 121.199.58.89";

    // 构建完整的命令字符串
    char fullCommand[100];
    strcpy(fullCommand, "echo ");
    strcat(fullCommand, password);
    strcat(fullCommand, " | ");
    strcat(fullCommand, command);
    // 执行命令
    int status = system(fullCommand);

    if (status == 0) {
        LOG_INFO("Exec cmd successful");
    } else {
        LOG_ERROR("Exec cmd Failed !");
    }

}